using System.Collections;
using UnityEngine;
using UnityEngine.Events;

/**
GameManager类，用于管理游戏进程
**/

public class GameManager : MonoBehaviour
{   
    private static GameManager _instance;
    public static GameManager instance{
        get{
            if(_instance == null){
                _instance = FindAnyObjectByType<GameManager>();
                if(_instance == null){
                    GameObject obj = new GameObject();
                    _instance = obj.AddComponent<GameManager>();
                }
            }
            return _instance;
        }
    }
    public static readonly float processTime = 0.1f;//协程进行时间
    
    /// <summary>
    /// 游戏状态节点
    /// </summary>
    public int node = 0;

    /// <summary>
    /// 游戏状态信息
    /// </summary>
    public string stateInfo = "无";
    public GameBase game;
    public Player player;

    /// <summary>
    /// 主协程
    /// </summary>
    public Coroutine process;

    /// <summary>
    /// 去往下一个状态的监听事件
    /// </summary>
    public UnityEvent<int, int> OnChange;

    
    /// <summary>
    /// 主进程事件
    /// </summary>
    [HideInInspector]
    public UnityEvent<int> OnProcess;

    /// <summary>
    /// 更改node
    /// </summary>
    /// <param name="next"></param>
    /// <returns></returns>
    public int ChangeTo(int next){
        OnChange?.Invoke(node,next);
        node = next;
        return node;
    }

    /// <summary>
    /// 切换到下一个节点
    /// </summary>
    /// <returns></returns>
    public int Next(){
        return ChangeTo(node + 1);
    }

    IEnumerator Process(){
        while(true){
            OnProcess?.Invoke(node);
            yield return new WaitForSeconds(processTime);
        }
    }

    private void Awake() {
        instance.process = StartCoroutine(Process());
    }

    private void OnDestroy() {
        StopCoroutine(process);
    }

}
